package com.suibibk.springCloud.gateway;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

@Configuration
public class GatewayConfig {
    @PostConstruct
    public void init(){
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Result r = null;
                if(throwable instanceof FlowException){
                    r = Result.error(100,"接口被限流了");
                }else if (throwable instanceof DegradeException){
                    r = Result.error(101,"服务降级了");
                }else if (throwable instanceof ParamFlowException){
                    r = Result.error(102,"热点参数限流了");
                }else if (throwable instanceof SystemBlockException){
                    r = Result.error(103,"系统规则");
                }else if (throwable instanceof AuthorityException){
                    r = Result.error(104,"授权规则不通过");
                }
                if(r==null){
                    r = Result.error(105,"当前请求人数过多，请稍后再试");
                }
                //自定义异常处理
                return ServerResponse.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(r));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}

